<template>
  <div>
    <div class="left-title">
      <div class="txt">{{ name }}</div>
      <el-button v-if="handle" v-permission="['LEFTTREE_ADD_BUTTON']" size="small"
                 type="primary" @click="addMeasur('')">+ 新增{{ name }}</el-button>
    </div>
    <el-input
      v-if="handle"
      v-model.trim="filterText"
      prefix-icon="el-icon-search"
      size="small"
      placeholder="请输入分类名称"
      maxlength="30"
      class="limit"
    />
    <el-tree
      ref="leftTree"
      class="left-tree"
      :empty-text="$store.getters.dataText"
      :data="treeList"
      :props="defaultProps"
      default-expand-all
      highlight-current
      node-key="id"
      :current-node-key="currentKey"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
      @node-click="handleNodeClick"
    >
      <div slot-scope="{ node, data }" class="custom-tree-node">
        <!-- <el-tooltip class="item" effect="dark" :content="node.label" placement="bottom-start">
          <div class="tree-name">{{ node.label }}</div>
        </el-tooltip> -->
        <overTooltip :content="data.typeName" />
        <template>
          <div v-if="handle && data.id !='' " :class="updateDisabled(data)? 'active' : 'btn'" @click.stop>
            <i v-permission="['LEFTTREE_UPDATE_BUTTON']" class="el-icon-edit-outline edit-btn" @click.stop="nameEdit(data)" />
            <i v-permission="['LEFTTREE_DEL_BUTTON']" class="el-icon-delete del-btn" :style="{}"
               @click.stop="nameDel(data)" />
          </div>
        </template>
      </div>
    </el-tree>
    <!-- 添加 -->
    <dtDialog
      :title="title"
      :visible.sync="measurVisible"
      :is-loading="measurLoading"
      @closeDialog="closeDialog"
      @comfirmBtn="confirm"
    >
      <el-form
        slot="content"
        ref="pointFormRef"
        :rules="rules"
        :model="formData"
        label-position="right"
        label-width="84px"
        style="width: 100%"
      >
        <el-form-item label="分类名称" prop="typeName">
          <el-input
            v-model.trim="formData.typeName"
            maxlength="15"
            show-word-limit
            placeholder="请输入分类名称"
            size="small"
          />
        </el-form-item>
        <el-form-item label="分类编码" prop="typeCode">
          <el-input
            v-model.trim="formData.typeCode"
            maxlength="20"
            show-word-limit
            placeholder="请输入分类编码"
            size="small"
            :disabled="formData.id?true:false"
          />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input
            v-model.trim="formData.remark"
            type="textarea"
            maxlength="200"
            :autosize="{minRows: 6, maxRows: 6}"
            show-word-limit
            placeholder="请输入描述"
            size="small"
          />
        </el-form-item>
      </el-form>
    </dtDialog>
  </div>
</template>

<script>
import overTooltip from './overTooltip.vue'
import { listType, addType, editType, delType } from '@/framework/api/applicationMag/applicationType'
import { checkAccountName, checkParameterName } from '@/framework/utils/validate'

export default {
  components: { overTooltip },
  props: {
    name: {
      type: String,
      default: '测点管理'
    },
    handle: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateTypeName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入分类名称'))
      } else if (!checkAccountName(value)) {
        callback(new Error('分类名称只能输入汉字、字母、数字'))
      } else callback()
    }
    const validateTypeCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入分类编码'))
      } else if (!checkParameterName(value)) {
        callback(new Error('分类编码只能输入字母、数字'))
      } else callback()
    }
    return {
      selectId: '',
      areaPopShow: false,
      formData: {},
      showTree: true,
      rules: {
        typeName: { required: true, trigger: 'blur', validator: validateTypeName },
        typeCode: { required: true, trigger: 'blur', validator: validateTypeCode }
      },
      title: '',
      measurVisible: false,
      measurLoading: false,
      filterText: '',
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentKey: ''
    }
  },
  computed: {
    dialogList() {
      return [{
        id: '0',
        name: '无',
        level: 0
      }, ...this.treeList]
    },
    tenantId() {
      return this.$store.state.user.tenantId
    }
  },
  watch: {
    filterText(val) {
      this.$refs.leftTree.filter(val)
    }
  },
  created() {
    this.getList()
  },

  methods: {
    getList(type) {
      listType().then((res) => {
        this.treeList = [{
          typeName: '全部',
          children: (res.data || []).map((item) => {
            return { ...item, children: [] }
          }),
          id: ''
        }]
        this.$emit('getTypeList', this.treeList)
        this.$nextTick(() => {
          if (type && !this.selectId) {
            this.$emit('treeClick', this.selectId)
          } else if (this.selectId) {
            this.$refs.leftTree.setCurrentKey(this.selectId)
          }
          this.currentKey = this.treeList[0].id
          this.$nextTick(() => {
            this.$refs.leftTree.setCurrentKey(this.currentKey)
          })
          this.handleNodeClick(this.treeList[0])
          // if (!this.selectId) {
          //   // this.selectId = this.treeList[0].id
          //   // this.$refs.leftTree.setCurrentKey(this.selectId)
          //   this.$emit('treeClick', this.selectId)
          // } else {
          //   this.$refs.leftTree.setCurrentKey(this.selectId)
          // }
        })
      })
    },
    closeDialog() {
      this.measurVisible = false
    },
    confirm() {
      this.$refs['pointFormRef'].validate((valid) => {
        if (valid) {
          this.measurLoading = true
          try {
            const fn = this.formData.id ? editType : addType
            const mes = this.formData.id ? '修改' : '新增'
            fn(this.formData).then((res) => {
              this.$dtModal.msgSuccess(`${mes}成功`)
              this.measurVisible = false
              this.getList()
            })
            this.measurLoading = false
          } catch (error) {
            this.measurLoading = false
          }
        } else {
          this.measurLoading = false
          return false
        }
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.typeName.indexOf(value) !== -1
    },
    addMeasur(data) {
      // 清空表单信息
      this.reset()
      // this.showTree = true
      // if (data) {
      //   this.showTree = false
      //   this.formData = {
      //     parentId: data.id,
      //     level: data.level + 1,
      //     name: data.className
      //   }
      // }
      this.title = `新增${this.name}`
      this.measurVisible = true
    },
    // 表单重置
    reset() {
      this.formData = {
        id: null,
        typeName: null,
        typeCode: null,
        remark: null
      }
      this.resetForm('pointFormRef')
    },
    handleNodeClick(row) {
      this.selectId = row.id
      this.$emit('treeClick', row.id)
    },
    nameEdit(data) {
      this.showTree = false
      this.reset()
      const { id, typeName, typeCode, remark } = data
      this.formData = {
        id,
        typeName,
        typeCode,
        remark
      }
      this.title = `修改${this.name}`
      this.measurVisible = true
    },
    nameDel(data) {
      this.$dtModal.confirm(`是否确认删除“${data.typeName}”？`).then(() => {
        return delType({ id: data.id, flag: 2 })
      }).then(() => {
        const temp = this.selectId
        temp === data.id && (this.selectId = '')
        this.getList(temp === data.id)
        this.$dtModal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    updateDisabled(data) {
      if (this.tenantId == '000000') {
        return false
      } else if (data.isDefault == 1) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

  <style lang="scss" scoped>
  .left-title{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  .txt{
    color: #131314;
    font-size: 14px;
    line-height: 24px;
    padding-left: 12px;
    position: relative;
    &::before{
      content: '';
      position: absolute;
      width: 4px;
      height: 16px;
      background: var(--themeColor);
      left:0;
      top: 4px;
    }
  }
  .left-tree{
    margin-top: 12px;
  }
    ::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
          background-color:var(--lightOpacity)
    }
  ::v-deep .el-tree-node__content:hover, .el-upload-list__item:hover{
    background-color:var(--lightOpacity)
  }
  ::v-deep .el-tree-node__content{
    overflow: hidden;
    margin: 1px 0px
  }
  .custom-tree-node{
    display: flex;
    align-items: center;
    overflow: hidden;
    width: 100%;
    .tree-name{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex:1;
    }
    .btn{
      margin-left: 24px;
      color: var(--themeColor);

    .edit-btn{
      margin-right: 8px;

    }
    .del-btn{
      color:#F56C6C ;

    }
  }
  }
  .active{
    margin-left: 24px;
    cursor:not-allowed;
    .edit-btn{
      margin-right: 8px;
      color: #cfd0d3;
      pointer-events:none;
    }
    .del-btn{
      pointer-events:none;
      color: #fab6b6;
    }
  }
  </style>
